package cn.hackcloud.javabase.reflect;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.Parameter;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

import org.junit.Test;

public class TestReflect {
	@Test
	public void test() {
		Class c = Person.class;
		Field[] fields = c.getFields();
		for (Field field : fields) {
			System.err.println(field.getName());
		}
		Field[] field2 = c.getDeclaredFields();
		for (Field field : field2) {
			System.err.println(field.getName());
		}
	}

	@Test
	public void test2() {
		Class c = Person.class;
		Field[] fields = c.getDeclaredFields();
		for (Field field : fields) {
			// 获取权限修饰符
			int i = field.getModifiers();
			String str1 = Modifier.toString(i);
			System.err.println(str1);
			// 获取属性的变量类型
			Class class1 = field.getType();
			System.err.println(class1.getName());
			System.err.println(field.getName());
		}
	}

	@Test
	public void test3() {
		Class c = Person.class;
		Method[] m1 = c.getDeclaredMethods();
		for (Method method : m1) {
			// 注解
			Annotation[] annotation = method.getAnnotations();
			// System.err.println(annotation);
			// 权限修饰符
			// System.err.println(Modifier.toString(method.getModifiers()));
			// 返回值类型
			Class zz = method.getReturnType();
			System.err.println(zz.getName());
			// 方法名
			// System.err.println(method.getName());
			// 形参列表
			System.err.println("{");
			Parameter[] p = method.getParameters();
			for (Parameter parameter : p) {
				System.err.println(parameter);
			}
			System.err.println("}");

		}
	}

	@Test
	public void test4() {
		Class c = Person.class;
		Type t = c.getGenericSuperclass();
		System.err.println(t);
	}

	// 获取父类的泛型
	@Test
	public void test5() {
		Class c = Person.class;
		Type t = c.getGenericSuperclass();
		ParameterizedType parameterizedType = (ParameterizedType) t;
		Type[] types = parameterizedType.getActualTypeArguments();
		System.err.println(types[0]);
	}

	@Test
	public void test6() throws Exception {
		Class c = Person.class;
		Field name = c.getField("name");
		Person p = (Person) c.newInstance();
		name.set(p, "赖军");
	
		Field age = c.getDeclaredField("id");
		age.setAccessible(true);
		age.set(p, 25);
		System.err.println(p);
	}
}
